package com.example.werewolf.entity;

import com.example.werewolf.common.Camp;
import com.example.werewolf.common.GameResult;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;


@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class GameEngine {
    private String systemRules;
    private List<Player> players;
    private List<GamePhase> phases;
    private int currentPhaseIndex;
    private List<Event> publicEvents = new ArrayList<>();

    public void startGame() {
        // 初始化玩家，开始游戏
    }

    public void nextPhase() {
        // 根据当前阶段推进到下一个阶段
    }

    public void executeAction(Player player, String action) {
        // 执行玩家的行动并更新游戏状态
    }

    public void incrementCurrentPhaseIndex() {
        this.currentPhaseIndex += 1;
    }

    /**
     * 判断游戏是否结束
     * @return
     */
    private GameResult checkGameResult() {
        long wolfCount = players.stream()
                .filter(Player::isAlive)
                .filter(p -> Camp.WEREWOLF == p.getCamp())
                .count();

        long godCount = players.stream()
                .filter(Player::isAlive)
                .filter(p -> Camp.GOOD_GUY == p.getCamp()) // 神职属于好人阵营
                .count();

        long villagerCount = players.stream()
                .filter(Player::isAlive)
                .filter(p -> Camp.VILLAGER == p.getCamp())
                .count();

        // 好人胜利：所有狼人出局
        if (wolfCount == 0) {
            return GameResult.GOOD_WINS;
        }

        // 狼人胜利 - 屠边规则
        // 屠神：所有神职死亡
        // 屠民：所有平民死亡
        if (godCount == 0 || villagerCount == 0) {
            return GameResult.WEREWOLF_WINS_BY_EDGE_KILL;
        }

        // 狼人胜利 - 人数均势
        long goodCount = godCount + villagerCount; // 所有好人数量
        if (wolfCount >= goodCount) {
            return GameResult.WEREWOLF_WINS_BY_NUMBERS;
        }

        // 游戏继续
        return GameResult.ONGOING;
    }

    public static List<Player> findPlayers(List<Player> players, String playerType) {
        return switch (playerType) {
            case "全体" -> players;
            case "存活玩家" -> players.stream().filter(Player::isAlive).toList();
            case "警下玩家" -> players.stream().filter(p -> !p.isSpeech()).toList();
            default -> players.stream().filter(player -> playerType.equals(player.getRole())).toList();
        };
    }
}

